

var maxProfit = function(prices: number[]): number {
    if (prices.length == 0) return 0;
    var min = prices[0], max = prices[0]
    var profit = max - min
    var i = 1;
    var newMin = min;
    while(i < prices.length) {
        if (newMin !== min && prices[i] - newMin > profit) {
            profit = prices[i] - newMin
            min = newMin
            max = prices[i]
        }
        else if (prices[i] > max) {
            max = prices[i]
            profit = max - min
        }
        else if (prices[i] < newMin) {
            newMin = prices[i]
        }
        i++
    }
    return profit;
};

//console.assert( maxProfit( [10000,9999,9998,9997,9996]) === 4)

console.assert( maxProfit( [4,7,1,2,11]) === 10)
console.assert( maxProfit( [7, 1, 5, 3, 6, 4]) === 5)
console.assert( maxProfit( [7, 6, 4, 3, 1]) === 0)


console.log('The END')